import { isNull, isNullOrUndef } from "./is";

export class Storage {
  /**
   *
   * @param {string} key
   * @param {string} value
   * @param {number} expire 毫秒
   * @returns
   */
  static set(key, value, expire) {
    let jsonValue = JSON.stringify({
      value,
      expire: isNullOrUndef(expire) ? null : new Date().getTime() + expire,
    });
    uni.setStorageSync(key, jsonValue);
  }

  static get(key) {
    let jsonValue = uni.getStorageSync(key);
    if (!jsonValue) return null;
    const { value, expire } = JSON.parse(jsonValue);
    if (isNull(expire)) return value;
    if (expire > new Date().getTime()) {
      return value;
    }
    return null;
  }

  static getExpire(key) {
    let jsonValue = uni.getStorageSync(key);
    const { expire } = jsonValue;
    return expire;
  }

  static remove(key) {
    uni.removeStorageSync(key);
  }
}
